package eBrain.model;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.sun.org.apache.xpath.internal.operations.Quo;

import eBrain.beans.Item;

public class SearchHandler {
	
	
	public static ArrayList search(HttpServletRequest request){
		
		HttpSession session = request.getSession();
		ArrayList<String> titels = (ArrayList<String>)session.getServletContext().getAttribute("titels");
		ArrayList<Item> items = new ArrayList<Item>();
		ArrayList<String> results = new ArrayList<String>();
		
		String query = request.getParameter("query");
		String[] queryarray = query.split(" ");
		
		for(int i = 0; i<queryarray.length; i++){
			for(int j = 0; j<titels.size(); j++){
				
				if (titels.get(j).contains(queryarray[i])){
					results.add(queryarray[i]);
				}
				else{
				if (frequency(titels.get(j), queryarray[i])!=0){
					results.add(queryarray[i]);
				}
				}
			}
		}
		
		return results;
	}
	
	public static int frequency( String source, String part ) 
	{ 
		  if ( source == null || source.isEmpty() || part == null || part.isEmpty() ) 
		    return 0; 
		 
		  int count = 0; 
		 
		  for ( int pos = 0; (pos = source.indexOf( part, pos ))!=-1; count++ ) 
		    pos += part.length(); 
		 
		  return count; 
		}
	

}
